<?php

namespace app\admin\controller;

use app\admin\model\AuthRule;
use think\Controller;
use think\Request;

class AuthRuleController extends BaseController
{
    /**
     * 权限列表
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $rules = AuthRule::paginate(5);
        return view('index', compact('rules'));
    }

    /**
     * 添加
     * @param Request $request
     * @return \think\response\View|void
     */
    public function add(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->post();
            $validate = $this->validate($data, [
                'name|权限名称' => 'require|unique:auth_rule',
                'title|中文名称' => 'require|unique:auth_rule',
            ]);
            if ($validate !== true) {
                //验证没有通过
                return $this->error($validate);
            }
            $data['create_at'] = time();
            $data['update_at'] = time();
            $res = AuthRule::create($data);
            if ($res) {
                return $this->success('添加成功', 'index');
            } else {
                return $this->error('添加失败', 'add');
            }
        }
        return view('add');
    }

    /**
     * 修改
     * @param Request $request
     * @param $id
     * @return \think\response\View|void
     * @throws \think\exception\DbException
     */
    public function edit(Request $request, $id)
    {
        $rule = AuthRule::get($id);
        if ($request->isPost()) {
            $data = $request->post();
            $validate = $this->validate($data, [
                'name|权限名称' => 'require',
                'title|中文名称' => 'require',
            ]);
            if ($validate !== true) {
                //验证没有通过
                return $this->error($validate);
            }
            $data['create_at'] = time();
            $data['update_at'] = time();
            $res = $rule->save($data);
            if ($res) {
                return $this->success('修改成功', 'index');
            } else {
                return $this->error('修改失败', 'edit');
            }
        }
        return view('edit', compact('rule'));
    }

    /**
     * 删除
     * @param $id
     * @throws \think\exception\DbException
     */
    public function del($id)
    {
        $rule = AuthRule::get($id);
        $res = $rule->delete();
        if ($res) {
            return $this->success('删除成功', 'index');
        } else {
            return $this->error('删除失败');
        }
    }
}
